﻿using Microsoft.Extensions.Options;
using ProjectTemplate.Identity.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ProjectTemplate.Identity.Services
{
    public class JwtFactory : IJwtFactory
    {
        private readonly JwtOptions _jwtOptions;

        //public JwtFactory(IOptions<JwtOptions> jwtOptions)
        //{
        //    _jwtOptions = jwtOptions.Value;
        //    ThrowIfInvalidOptions(_jwtOptions);
        //}
        //public async Task<JwtToken> GenerateJwtToken(ClaimsIdentity claimsIdentity)
        //{
        //    claimsIdentity.AddClaims(new Claim[]
        //   {
        //        //new Claim(JwtRegisteredClaimNames.Sub, user.Username),
        //        new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
        //        new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
        //   });

        //    var tokenHandler = new JwtSecurityTokenHandler();
        //    var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
        //    {
        //        Issuer = _jwtOptions.Issuer,
        //        Audience = _jwtOptions.Audience,
        //        Subject = claimsIdentity,
        //        NotBefore = _jwtOptions.NotBefore,
        //        Expires = _jwtOptions.Expiration,
        //        SigningCredentials = _jwtOptions.SigningCredentials,
        //    });

        //    return new JwtToken
        //    {
        //        JwtId = token.Id,
        //        AccessToken = tokenHandler.WriteToken(token),
        //    };
        //}

        public class JwtToken
        {
            public string? JwtId { get; set; }
            public string? AccessToken { get; set; }
        }

        //private static void ThrowIfInvalidOptions(JwtOptions options)
        //{
        //    if (options == null) throw new ArgumentNullException(nameof(options));

        //    if (options.ValidFor <= TimeSpan.Zero)
        //    {
        //        throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(JwtOptions.ValidFor));
        //    }

        //    if (options.SigningCredentials == null)
        //    {
        //        throw new ArgumentNullException(nameof(JwtOptions.SigningCredentials));
        //    }

        //    if (options.JtiGenerator == null)
        //    {
        //        throw new ArgumentNullException(nameof(JwtOptions.JtiGenerator));
        //    }
        //}

        /// <returns>Date converted to seconds since Unix epoch (Jan 1, 1970, midnight UTC).</returns>
        private static long ToUnixEpochDate(DateTime date)
          => (long)Math.Round((date.ToUniversalTime() -
                               new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero))
                              .TotalSeconds);
    }
}
